package softtech.app.secretcaller;

import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

public class ControlsGetAllContactsFromServer extends AsyncTask<Void, Void, Void> {

	final String TAG = "CONTROL GET ALL CONTACT FROM SERVER";

	Context context;
	
	DatabaseHandler db;
	
	String result_from_server;
	
	DatabaseUser mUser;
	
	int page;
	
	static int totals_page;
	
	public ControlsGetAllContactsFromServer(Context context , DatabaseUser user ){
		this(context, user , 0);
	}
	
	public ControlsGetAllContactsFromServer(Context context , DatabaseUser user , int page ){
		super();
		this.context = context;
		db = new DatabaseHandler(context);
		result_from_server = "";
		mUser = user;
		if(page>0){
			this.page = page;
		}else{
			this.page =0 ;
		}
		totals_page = 0;
	}
	
	@Override
	protected Void doInBackground(Void... params) {
		HttpRequest request = new HttpRequest();
		List<NameValuePair> listPair = mUser.toListNameValuePair();
		listPair.add(new BasicNameValuePair("page", Integer.toString(page)));
		result_from_server = request.makeServiceCall(ConstantsFileName.URL_CONTACT_GETALL, HttpRequest.POST , listPair);
		return null;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		if(!ToolsSaveFile.checkStringNotNull(result_from_server)){
			return;
		}else{
			try{
				
				//**** Parse data to list contact
				JSONObject jsonObject = new JSONObject(result_from_server);
				int success = jsonObject.getInt(ConstantsFileName.success_field);
				if(success <= 0 ){
					return;
				}
				
				JSONObject data = jsonObject.getJSONObject(ConstantsFileName.data_field);
				
				totals_page = data.getInt(ConstantsFileName.total_pages_field);
				
				JSONArray arrContactFromServer = data.getJSONArray(ConstantsFileName.list_contact);
				
				//ArrayList<DatabaseContact> listContacts = new ArrayList<DatabaseContact>();
				
				
				//**** Save List Contact
				for(int i=0 ; i< arrContactFromServer.length() ; i ++ ){
					JSONObject obj = arrContactFromServer.getJSONObject(i);
					int id = obj.getInt("id");
					int user_id = obj.getInt(DatabaseContact.KEY_ID_USER);
					String name = obj.getString(DatabaseContact.KEY_CONTACT_NAME);
					String phone = obj.getString(DatabaseContact.KEY_PHONE);
					
					DatabaseContact ct2 = db.getContactFromPhoneNumber(phone, user_id);
					DatabaseContact ct1 =null;
					try{
						ct1 = db.getContact(id, user_id);
					}catch(Exception e){
						e.printStackTrace();
					}
					
					if( ct2!=null && !ct2.equals(null)){
						// trung` so
						// check trung` ten
						if(ct2.getContactName().equals(name)){
							if(ct2.get_Id() == -1){
								ct2.set_Id(id);
								ct2.setIsSync(1);
								db.updateContact(ct2.getPrimaryKey() , ct2);
							}else if(ct2.get_Id()== id){
							}
						}else{
							if(ct2.get_Id() == -1){
								ct2.set_Id(id);
								ct2.setIsSync(-1);
								db.updateContact(ct2.getPrimaryKey() , ct2);
							}else if(ct2.get_Id()== id){
							}
						}
						
					}else{
						DatabaseContact ct = new DatabaseContact(id, name, phone, user_id);
						ct.setIsSync(1);
						db.addContact(ct);
						
						// khong trung so
						if(ct1!=null ){
							
						}else{
							
						}
					}
					
					
				}
				
				//**** Post to broadcast
				Intent intent_finish = new Intent(ConstantsFileName.TAG_BROADCAST);
				intent_finish.putExtra(ConstantsFileName.TAG_FINISH_UPDATE , true);
		        context.sendBroadcast(intent_finish);
				
				
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		try{
			if (db != null) {
				db.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	

}
